﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Threading;
using System.Threading;
using System.Collections.ObjectModel;
using Microsoft.Phone.Controls.Maps;
using System.Device.Location;
using System.Windows.Media.Imaging;
using Microsoft.Phone.Reactive;
using System.Windows.Controls.Primitives;


namespace ChiantiPhoneListApp
{
    public delegate void Refresh();
    public delegate void OnLocationChange(object e, GeoPositionChangedEventArgs<GeoCoordinate> args);
    public delegate void OnSelectedDealChanged();
    public delegate void OnSelectedDealExpired();
    public delegate void OnDealExpired(ChiantiServiceReference5.Deal expiredDeal);

    public partial class PanoramaPage1 : PhoneApplicationPage
    {
        private MapLayer                            myRouteLayer;
        private MapLayer                            pushpinLayer;
        private MapLayer                            locationLayer;
        private MapLayer                            nearbyDealLayer;
        private MapLayer                            nearbyDealLocationLayer;
        private LoadingControl                      loadingControl;
        private Popup                               popup;
        private RouteService2.RouteServiceClient    routeClient;
        private ObservableCollection<Pushpin>       pushpins;

        private Timer                               dispatchTimer;
        private Timer                               expiryTimer;
        
        public RouteService2.RouteServiceClient     RouteClient
        {
            get
            {
                if (routeClient == null)
                {
                    routeClient = new RouteService2.RouteServiceClient("BasicHttpBinding_IRouteService");
                    routeClient.CalculateRouteCompleted += new EventHandler<RouteService2.CalculateRouteCompletedEventArgs>(_routeClient_CalculateRouteCompleted);

                }
                return routeClient;

            }
            set { routeClient = value; }
        }

        public Timer                                DispatchTimer
        {
            get
            {

                return dispatchTimer;
            }
            set { dispatchTimer = value; }
        }

        public Timer                                ExpiryTimer
        {
            get { return expiryTimer; }
            set { expiryTimer = value; }
        }

        public PanoramaPage1()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(PanoramaPage1_Loaded);
            DataContext = App.ViewModel;
            App.ViewModel.OnViewModelUpdate += OnViewModelRefreshed;
            App.ViewModel.OnSelectedDealChanged += OnSelectedDealChanged;
            App.LocationService.OnLocationChange += OnUserLocationChanged;
            App.ViewModel.OnSelectedDealExpired += OnSelectedDealExpired;
            App.ViewModel.OnDealExpired += OnDealExpired;
            TimerCallback callback = new TimerCallback(dispatchTimer_Tick);
          //  dispatchTimer = new Timer(callback, null, 0, Constants.TIMER_INTERVAL);
            
            pushpins = new ObservableCollection<Pushpin>();

            // Add a map layer in which to draw the route.
            myRouteLayer = new MapLayer();
            pushpinLayer = new MapLayer();
            locationLayer = new MapLayer();
            nearbyDealLayer = new MapLayer();
            nearbyDealLocationLayer = new MapLayer();

            popup = new Popup();
            loadingControl = new LoadingControl();
            popup.Child = loadingControl;
            popup.IsOpen = true;

            TimerCallback expiryCallback = new TimerCallback(expiryTime_Tick);
            expiryTimer = new Timer(expiryCallback, null, 0, Constants.EXPIRY_TIMER_INTERVAL);


        }
        /// <summary>
        /// Called when the route service client has finished rendering a route to a new destination. Will draw route and end points on the map.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void _routeClient_CalculateRouteCompleted(object sender, RouteService2.CalculateRouteCompletedEventArgs e)
        {
            if ((e.Result.ResponseSummary.StatusCode == RouteService2.ResponseStatusCode.Success))
            {
                tb_TitleBusinessName.Text = string.Format("{0}", App.ViewModel.SelectedBusiness.Name);
                tb_TitleBusinessAddress.Text =  string.Format("{0}", App.ViewModel.SelectedBusiness.StreetAddress);
                tb_TitleBusinessCityStateZip.Text = string.Format("{0},{1},{2}", App.ViewModel.SelectedBusiness.City,App.ViewModel.SelectedBusiness.State,App.ViewModel.SelectedBusiness.ZipCode);

                tb_Distance.Text = string.Format("{0} meters away or about a {1} minute {2}", e.Result.Result.Summary.Distance, e.Result.Result.Summary.TimeInSeconds/60,"walk"); 
                
                // Set properties of the route line you want to draw.
                Color routeColor = Colors.Blue;
                SolidColorBrush routeBrush = new SolidColorBrush(routeColor);
                MapPolyline routeLine = new MapPolyline();
                routeLine.Locations = new LocationCollection();
                routeLine.Stroke = routeBrush;
                routeLine.Opacity = 0.65;
                routeLine.StrokeThickness = 5.0;

                // Retrieve the route points that define the shape of the route.
                LocationCollection locationPoints = new LocationCollection();
                foreach (RouteService2.Location p in e.Result.Result.RoutePath.Points)
                {
                    GeoCoordinate coordinate = new GeoCoordinate(p.Latitude, p.Longitude, p.Altitude);
                    routeLine.Locations.Add(coordinate);
                    locationPoints.Add(coordinate);
                }



                // Add the route line to the new layer.
                myRouteLayer.Children.Add(routeLine);
                locationPoints.Add(new GeoCoordinate(App.LocationService.CurrentLatitude.ToDecimal(), App.LocationService.CurrentLongitude.ToDecimal()));
                LocationRect boundingRectangle = CreateLocationRectangle(locationPoints);
                DealMap.SetView(boundingRectangle);
              
                
                MapPolygon startPoint = new MapPolygon();
                startPoint.Width = 10;
                startPoint.Height = 10;
                startPoint.Fill = new SolidColorBrush(Colors.Red);
                startPoint.Opacity = 0.65;
                startPoint.Locations = new LocationCollection();
                startPoint.Locations.Add(new GeoCoordinate(App.LocationService.CurrentLatitude.ToDecimal(), App.LocationService.CurrentLongitude.ToDecimal()));
                myRouteLayer.Children.Add(startPoint);


                MapPolygon endPoint = new MapPolygon();
                endPoint.Width = 10;
                endPoint.Height = 10;
                endPoint.Fill = new SolidColorBrush(Colors.Red);
                endPoint.Opacity = 0.65;
                endPoint.Locations = new LocationCollection();
                endPoint.Locations.Add(new GeoCoordinate(App.ViewModel.SelectedBusiness.Latitude, App.ViewModel.SelectedBusiness.Longitude));
                myRouteLayer.Children.Add(endPoint);

                Pushpin pushpin2 = new Pushpin();
                pushpin2.Location = endPoint.Locations[0];
                pushpin2.Foreground = new SolidColorBrush(Colors.White);
                string destinationDescription = string.Format(App.ViewModel.SelectedBusiness.Name + "\n" + App.ViewModel.SelectedDeal.Title);                pushpin2.Content = destinationDescription;

                pushpinLayer.AddChild(pushpin2, pushpin2.Location);
                

            }
 
        }

        private LocationRect CreateLocationRectangle(LocationCollection points)
        {
            double northLat = 0;
            double southLat = 0;
            double eastLong = 0;
            double westLong = 0;

            foreach (GeoCoordinate location in points)
            {
                if (northLat == 0 || location.Latitude > northLat)
                {
                    northLat = location.Latitude;
                }
                
                if (southLat == 0 || location.Latitude < southLat)
                {
                    southLat = location.Latitude;
                }

                if (eastLong == 0 || location.Longitude > eastLong)
                {
                    eastLong = location.Longitude;
                }
                
                if (westLong == 0 || location.Longitude < westLong)
                {
                    westLong = location.Longitude;
                }
            }

            northLat += .0020;
            westLong -= .0020;
            eastLong += .0020;
            southLat -= .0020;
            return new LocationRect(northLat, westLong, southLat, eastLong);

        }
        private LocationCollection DrawACircle(GeoCoordinate oLoc, double dRadius)
        {
            
            LocationCollection retVal = new LocationCollection();
            
            double earthRadius = Constants.RADIUS_OF_EARTH_METERS;
            double lat = oLoc.Latitude * (Math.PI / 180);
            double lon = oLoc.Longitude * (Math.PI / 180);
            double d = dRadius / earthRadius;

            for (int x = 0; x <= 360; x++)
            {
                var brng = x * (Math.PI / 180); //radians 
                var latRadians = Math.Asin(Math.Sin(lat) * Math.Cos(d) + Math.Cos(lon) * Math.Sin(d) * Math.Cos(brng));
                var lngRadians = lon + Math.Atan2(Math.Sin(brng) * Math.Sin(d) * Math.Cos(lat), Math.Cos(d) - Math.Sin(lat) * Math.Sin(latRadians));
                var pt = new GeoCoordinate(180.0 * latRadians / Math.PI, 180.0 * lngRadians / Math.PI);
                retVal.Add(pt);
            }

            return retVal;
        }



        /// <summary>
        /// Timer is used to trigger a re-evaluation of the current user's position in regards to the view model cache
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dispatchTimer_Tick(object stateinfo)
        {           
            Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    App.ViewModel.RevaluateExpiredDeals();
                    
                    if(App.ViewModel.SelectedDeal == null && App.LocationService.CurrentLongitude != null && App.LocationService.CurrentLatitude != null)
                    {
                        ChiantiServiceReference5.Deal closestDeal = App.ViewModel.GetClosestDeal(App.LocationService.CurrentLatitude, App.LocationService.CurrentLongitude);
                        if (closestDeal != null)
                        {
                            App.ViewModel.SelectDeal(closestDeal.ID);
                        }
                        else
                        {
                            sp_ActiveBusiness.Visibility = System.Windows.Visibility.Collapsed;
                            sp_ActiveDeal.Visibility = System.Windows.Visibility.Collapsed;
                            tb_ExpiryCountdown.Visibility = System.Windows.Visibility.Collapsed;
                            sp_Buttons.Visibility = System.Windows.Visibility.Collapsed;
                            sp_ActiveDeal.DataContext = null;
                            sp_ActiveBusiness.DataContext = null;
                            img_DealImage.Visibility = System.Windows.Visibility.Collapsed;
                            tb_ActiveDealMsg.Visibility = System.Windows.Visibility.Visible;
                            tb_ActiveDealMsg.Text = "There are currently no active deals in your area";
                        }
                    }

                    if (App.ViewModel.SelectedDeal != null)
                    {
                        TimeSpan timeTillExpiry = (App.ViewModel.SelectedDeal.ExpiryDate - DateTime.Now);
                        string expiresInString = Utilities.CreateExpiresInString(timeTillExpiry);
                        tb_ExpiryCountdown.Text = expiresInString;
                    }
                    App.ViewModel.RevaluateDealSummaries();


                });
            

        }

       
        /* Recalculates the expiry clock if there is an active deal */
        /// </summary>
        /// <param name="stateinfo"></param>
        private void expiryTime_Tick(object stateinfo)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    App.ViewModel.RevaluateExpiredDeals();
                    if (App.ViewModel.SelectedDeal != null)
                    {
                        TimeSpan timeTillExpiry = (App.ViewModel.SelectedDeal.ExpiryDate - DateTime.Now);
                        string expiresInString = Utilities.CreateExpiresInString(timeTillExpiry);
                        tb_ExpiryCountdown.Text = expiresInString;
                    }
                    App.ViewModel.RevaluateDealSummaries();
                
                
                });
        }

        /// <summary>
        /// Called by the view model when the currently selected deal has expired.
        /// </summary>
        void OnSelectedDealExpired()
        {
            rec_Expired.Visibility = System.Windows.Visibility.Visible;
            
        }

        void OnDealExpired(ChiantiServiceReference5.Deal expiredDeal)
        {
            //RemoveDealFromNearbyDealMap(expiredDeal);
            //RefreshDealListing();
        }

        void OnSelectedDealChanged()
        {
            UpdateSelectedDealPane();
            UpdateDealMap();
            //RedrawNearbyDealMap();
        }

        private void UpdateSelectedDealPane()
        {
            rec_Expired.Visibility = System.Windows.Visibility.Collapsed;

            if (App.ViewModel.SelectedDeal != null)
            { 
                sp_ActiveBusiness.Visibility = System.Windows.Visibility.Visible;
                sp_ActiveDeal.Visibility = System.Windows.Visibility.Visible;
                sp_ActiveDeal.DataContext = App.ViewModel.SelectedDeal;
                sp_ActiveBusiness.DataContext = App.ViewModel.SelectedBusiness;
                tb_ActiveDealMsg.Visibility = System.Windows.Visibility.Collapsed;
                tb_ExpiryCountdown.Visibility = System.Windows.Visibility.Visible;
                sp_Buttons.Visibility = System.Windows.Visibility.Visible;
                img_DealImage.Visibility = System.Windows.Visibility.Visible;

                BitmapImage bmpImage = new BitmapImage();
                bmpImage.UriSource = new Uri("/Resources/IMAGE_071.jpg", UriKind.Relative);
                img_DealImage.Source = bmpImage;
            }
            else
            {
                sp_ActiveBusiness.Visibility = System.Windows.Visibility.Collapsed;
                sp_ActiveDeal.Visibility = System.Windows.Visibility.Collapsed;
                tb_ExpiryCountdown.Visibility = System.Windows.Visibility.Collapsed;
                sp_Buttons.Visibility = System.Windows.Visibility.Collapsed;
                sp_ActiveDeal.DataContext = null;
                sp_ActiveBusiness.DataContext = null;
                img_DealImage.Visibility = System.Windows.Visibility.Collapsed;
                tb_ActiveDealMsg.Visibility = System.Windows.Visibility.Visible;
                tb_ActiveDealMsg.Text = "There are currently no active deals in your area";
            }
        }

        void RefreshDealListing()
        {
            App.ViewModel.LoadData(App.LocationService.CurrentLatitude,
                                   App.LocationService.CurrentLongitude,
                                   Constants.NEARBY_DEAL_RADIUS);

        }

        private void PanoramaPage1_Loaded(object sender, RoutedEventArgs e)
        {
            // Add a map layer in which to draw the route.
           
            DealMap.Children.Add(myRouteLayer);
            DealMap.Children.Add(pushpinLayer);
            DealMap.Children.Add(locationLayer);
            DealZones.Children.Add(nearbyDealLayer);
            DealZones.Children.Add(nearbyDealLocationLayer);
            mit_DealZones.DataContext = App.ViewModel.DealSummaries;
            mit_DealZones.ItemsSource = App.ViewModel.DealSummaries;
            RefreshDealListing();
           
        }

        /// <summary>
        /// Called whenever the underlying view model has been refreshed
        /// </summary>
        private void OnViewModelRefreshed()
        {
            this.Dispatcher.BeginInvoke(() =>
            {
                this.popup.IsOpen = false;
                if (App.ViewModel.SelectedDeal == null)
                {
                    sp_ActiveBusiness.Visibility = System.Windows.Visibility.Collapsed;
                    sp_ActiveDeal.Visibility = System.Windows.Visibility.Collapsed;
                    tb_ExpiryCountdown.Visibility = System.Windows.Visibility.Collapsed;
                    sp_Buttons.Visibility = System.Windows.Visibility.Collapsed;
                    sp_ActiveDeal.DataContext = null;
                    sp_ActiveBusiness.DataContext = null;
                    img_DealImage.Visibility = System.Windows.Visibility.Collapsed;
                    tb_ActiveDealMsg.Visibility = System.Windows.Visibility.Visible;
                    tb_ActiveDealMsg.Text = "There are currently no active deals in your area";
                }
                RedrawNearbyDealMap();
            }
            );
        }


        /// <summary>
        /// When executed, will refresh the deal map with the currently active deal in the phone
        /// </summary>
        private void UpdateDealMap()
        {

            if (App.ViewModel.SelectedDeal != null)
            {
                ChiantiServiceReference5.Deal activeDeal = App.ViewModel.SelectedDeal;
                ChiantiServiceReference5.Business activeBusiness = App.ViewModel.SelectedBusiness;

               
                RouteService2.RouteRequest routeRequest = CreateRouteRequest(App.LocationService.CurrentLatitude,
                                                                           App.LocationService.CurrentLongitude,
                                                                           new ChiantiServiceReference5.Position(activeBusiness.Latitude),
                                                                           new ChiantiServiceReference5.Position(activeBusiness.Longitude));

                RouteClient.CalculateRouteAsync(routeRequest);

            }

        }

        private void RedrawNearbyDealMap()
        {
            LocationCollection dealLocations = new LocationCollection();
            GeoCoordinate currentUserLocation = new GeoCoordinate(App.LocationService.CurrentLatitude.ToDecimal(), App.LocationService.CurrentLongitude.ToDecimal());
            dealLocations.Add(currentUserLocation);

            foreach (ChiantiServiceReference5.DealSummary summary in App.ViewModel.DealSummaries)
            {
                dealLocations.Add(summary.Location);
            }
            DealZones.SetView(CreateLocationRectangle(dealLocations));
        /*
            nearbyDealLayer.Children.Clear();
            nearbyDealLocationLayer.Children.Clear();

            List<ChiantiServiceReference5.Deal> nearbyDealList = App.ViewModel.GetDeals(App.LocationService.CurrentLatitude, 
                                                                                        App.LocationService.CurrentLongitude, 
                                                                                        Constants.NEARBY_DEAL_RADIUS);

            LocationCollection dealLocations = new LocationCollection();
            GeoCoordinate currentUserLocation = new GeoCoordinate(App.LocationService.CurrentLatitude.ToDecimal(), App.LocationService.CurrentLongitude.ToDecimal());
            dealLocations.Add(currentUserLocation);
            int count = 1;

            UpdateUserLocationOnNearbyDealMap();

            //Draw each of the nearby deals on the map
            foreach (ChiantiServiceReference5.Deal nearbyDeal in nearbyDealList)
            {
                ChiantiServiceReference5.DealBid dealBid = App.ViewModel.GetDealBid(nearbyDeal.ID);
                ChiantiServiceReference5.Business business = App.ViewModel.GetBusiness(nearbyDeal.BusinessID);
                GeoCoordinate businessLocation = new GeoCoordinate(business.Latitude, business.Longitude);
                LocationCollection dealLocationPoints = DrawACircle(businessLocation, dealBid.Radius);

                Pushpin dealPushpin = CreateDealPushpin(count, nearbyDeal, business);
                nearbyDealLayer.AddChild(dealPushpin, businessLocation);
                dealLocations.Add(businessLocation);                
                count++;
            }
            */
       

        }

        /// <summary>
        /// Called when a deal is either deleted from the system or if it has expired
        /// </summary>
        private void RemoveDealFromNearbyDealMap(ChiantiServiceReference5.Deal dealToRemove)
        {
            Pushpin pinToRemove = null;
            foreach (UIElement element in nearbyDealLayer.Children)
            {
                Pushpin pin = element as Pushpin;
                if (pin.Name == dealToRemove.ID.ToString())
                {
                    pinToRemove = pin;
                }
            }

            if (pinToRemove != null)
            {
                nearbyDealLayer.Children.Remove(pinToRemove);
            }
        }

       

        private Pushpin CreateDealPushpin(int count, ChiantiServiceReference5.Deal nearbyDeal, ChiantiServiceReference5.Business business)
        {
            Pushpin pushpin = new Pushpin();
            GeoCoordinate businessLocation = new GeoCoordinate(business.Latitude, business.Longitude);

            pushpin.Name = nearbyDeal.ID.ToString();           
            pushpin.Location = businessLocation;
            

            return pushpin;
        }

       
        private string CreateNearbyDealDescription(int index,ChiantiServiceReference5.Deal nearbyDeal, ChiantiServiceReference5.DealBid dealBid, ChiantiServiceReference5.Business business)
        {
            GeoCoordinate currentUserLocation = new GeoCoordinate(App.LocationService.CurrentLatitude.ToDecimal(), App.LocationService.CurrentLongitude.ToDecimal());
            double distance = App.LocationService.GetDistanceInMeters(App.LocationService.CurrentLongitude, App.LocationService.CurrentLatitude, new ChiantiServiceReference5.Position(business.Longitude), new ChiantiServiceReference5.Position(business.Latitude));
            TimeSpan timeTillExpiry = (nearbyDeal.ExpiryDate-DateTime.Now);
            return string.Format("Deal {0} expires in {1}:{2}:{3} and is {1} meters away",index,timeTillExpiry.Days,timeTillExpiry.Hours,timeTillExpiry.Minutes, distance);

        }

        private RouteService2.RouteRequest CreateRouteRequest(ChiantiServiceReference5.Position startLatitude,
                                                              ChiantiServiceReference5.Position startLongitude,
                                                              ChiantiServiceReference5.Position endLatitude,
                                                              ChiantiServiceReference5.Position endLongitude)
        {
            RouteService2.RouteRequest retVal = new RouteService2.RouteRequest();
            retVal.Credentials = new RouteService2.Credentials();
            retVal.Credentials.ApplicationId = ((ApplicationIdCredentialsProvider)DealMap.CredentialsProvider).ApplicationId;
            retVal.Options = new RouteService2.RouteOptions();
            retVal.Options.RoutePathType = RouteService2.RoutePathType.Points;
            retVal.Options.Mode = RouteService2.TravelMode.Walking;
            //retVal.Options.Mode = RouteService2.TravelMode.Walking;
            ObservableCollection<RouteService2.Waypoint> waypoints = new ObservableCollection<RouteService2.Waypoint>();


            RouteService2.Waypoint originWaypoint = new RouteService2.Waypoint();
            originWaypoint.Description = "Your current position";
            originWaypoint.Location = new RouteService2.Location();
            originWaypoint.Location.Latitude = startLatitude.ToDecimal();
            originWaypoint.Location.Longitude = startLongitude.ToDecimal();

            RouteService2.Waypoint destinationWaypoint = new RouteService2.Waypoint();
            destinationWaypoint.Description = "Destination";
            destinationWaypoint.Location = new RouteService2.Location();
            destinationWaypoint.Location.Latitude = endLatitude.ToDecimal();
            destinationWaypoint.Location.Longitude = endLongitude.ToDecimal();

            waypoints.Add(originWaypoint);
            waypoints.Add(destinationWaypoint);


            retVal.Waypoints = waypoints.ToArray();



            return retVal;
        }



        // Event handler for location data. This invokes code on the
        // page's main thread.
        private void OnUserLocationChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                UpdateUserLocationOnMap();
                UpdateUserLocationOnNearbyDealMap();

            }

                );
        }

        void UpdateUserLocationOnMap()
        {
            UpdateUserLocationOnMapLayer("CurrentLocation", locationLayer);           
        }

        void UpdateUserLocationOnMapLayer(string pushpinName, MapLayer mapLayer)
        {
            //locationLayer.Children.Clear();
            GeoCoordinate currentLocation = new GeoCoordinate(App.LocationService.CurrentLatitude.ToDecimal(), App.LocationService.CurrentLongitude.ToDecimal());
            Pushpin pushpin = GetPushpinFromMap(pushpinName, mapLayer);

            if (pushpin == null)
            {
                mapLayer.Children.Clear();
                pushpin = CreateUserLocationPushpin(pushpinName);
                pushpin.Location = currentLocation;
                mapLayer.AddChild(pushpin, currentLocation);
            }
            else
            {
                pushpin.Location = currentLocation;
                mapLayer.Children.Remove(pushpin);
                mapLayer.AddChild(pushpin, currentLocation);
            }
            
        }
        private static Pushpin CreateUserLocationPushpin(string name)
        {
            Pushpin pushpin = new Pushpin();
            pushpin.Name = name ;
            pushpin.Style = Application.Current.Resources["PushpinStyle"] as Style;
            Image image = new Image();
            BitmapImage bmpImage = new BitmapImage();
            bmpImage.UriSource = new Uri("/Resources/customPin.png", UriKind.Relative);
            image.Source = bmpImage;
            pushpin.Content = image;
            return pushpin;
        }

        private Pushpin GetPushpinFromMap(string name, MapLayer locationLayer)
        {
            Pushpin retVal = null;
            foreach (UIElement element in locationLayer.Children)
            {
                Pushpin pushpin = (Pushpin)element;
                if (pushpin.Name == name)
                {
                    retVal = pushpin;
                    break;
                }
            }
            return retVal;
        }

        void UpdateUserLocationOnNearbyDealMap()
        {
            UpdateUserLocationOnMapLayer("CurrentLocationDealZone", nearbyDealLocationLayer);
        }

        /*
        //When an item on the list is selected
        private void lb_ActiveDealList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ChiantiServiceReference5.DealSummary dealSummary = lb_ActiveDealList.SelectedItem as ChiantiServiceReference5.DealSummary;
            if (dealSummary != null)
            {
                App.ViewModel.SelectDeal(dealSummary.DealID);
                p_Pivot.SelectedIndex = 0;
            }
        }
            
        
        */

    }
}